﻿
using NetworkPower.DataModel.Models;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace NetworkPower.UI
{
    /// <summary>
    /// EditProject.xaml 的交互逻辑
    /// </summary>
    public partial class EditProject : Window
    {
        NetworkPowerContext context = new NetworkPowerContext();
        private Project project = null;
        public EditProject()
        {
            InitializeComponent();
        }

        public EditProject(Project project)
            : this()
        {
            this.project = project;
            this.txtProjectName.Text = project.ProjectName;
            LoadVoltages();
        }

        private void LoadVoltages()
        {
            var datasouce = context.Voltages.Where(v => v.ProjectID == project.ProjectID).OrderBy(v => v.VoltageValue).ToList();
            lbVolt.ItemsSource = datasouce;
            lbVolt.DisplayMemberPath = "VoltageValue";
        }

        private void LoadSeperatorType()
        {
            var selectedValtageId = (lbVolt.SelectedItems[0] as Voltage).VoltageID;
            var datasouce = context.SeperatorTypes.Where(s => s.VoltageID == selectedValtageId).OrderBy(s => s.SeperatorValue).OrderBy(s => s.SeperatorValue).ToList();
            lbSeperatorType.ItemsSource = datasouce;
            lbSeperatorType.DisplayMemberPath = "SeperatorValue";
        }

        private void LoadUnitAndSeperatorName()
        {
            var selectedSeperatorTypeId = (lbSeperatorType.SelectedItems[0] as SeperatorType).SeperatorTypeID;
            var datasource = context.Units.Where(u => u.SeperatorTypeID == selectedSeperatorTypeId).OrderBy(s => s.UnitName).ToList();
            dataGridView1.ItemsSource = datasource;
        }

        private void btnInportData_Click(object sender, RoutedEventArgs e)
        {
            if (lbVolt.SelectedItems.Count < 1)
            {
                System.Windows.Forms.MessageBox.Show("请选择电压等级！");
                return;
            }
            if (lbSeperatorType.SelectedItems.Count < 1)
            {
                System.Windows.Forms.MessageBox.Show("请选择间隔类型！");
                return;
            }
            if (dataGridView1.SelectedItems.Count < 1)
            {
                System.Windows.Forms.MessageBox.Show("请选择安装单位和间隔名称！");
                return;
            }
            var unitComposite = SaveUnitComposite();
            if (unitComposite == null)
                return;
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            var rs = fbd.ShowDialog();
            if (rs == System.Windows.Forms.DialogResult.OK)
            {
                string[] files = Directory.GetFiles(fbd.SelectedPath);
                foreach (string file in files)
                {
                    string fileName = System.IO.Path.GetFileName(file);
                    if (!isExistEquipment(fileName) && (System.IO.Path.GetExtension(fileName).Equals(".xls") || System.IO.Path.GetExtension(fileName).Equals(".xlsx")))
                    {
                        GetFromExcelFile(file, unitComposite);
                    }
                }
                System.Windows.Forms.MessageBox.Show("完成保存！");
                this.Close();
            }
        }
        private bool isExistEquipment(string fileName)
        {
            return context.Set<Equipment>().Any(a => a.EquipmentName.Equals(fileName));
        }

        public void GetFromExcelFile(string filePath, UnitComposite unitComposite)
        {
            IWorkbook wk = null;
            int rowIndex = 0;
            try
            {
                var equipment = SaveSingleEquipment(filePath, unitComposite);
                if (equipment == null)
                    return;

                wk = GetWorkBook(filePath);
                for (int i = 0; i < wk.NumberOfSheets; i++)
                {
                    string generalTerminal = string.Empty;
                    ISheet sheet = wk.GetSheetAt(i);
                    var department = SaveDepartment(sheet.SheetName, i, equipment.EquipmentID);
                    if (department == null)
                    {
                        return;
                    }

                    IRow row = sheet.GetRow(0);
                    short PreviousColor = -1;
                    Guid PreviousGuid = Guid.Empty;
                    for (int j = 1; j <= sheet.LastRowNum; j++)
                    {
                        rowIndex++;
                        row = sheet.GetRow(j);

                        if (row != null)
                        {
                            LoopLine pc = new LoopLine();
                            pc.RowIndex = rowIndex;
                            pc.LoopLineId = Guid.NewGuid();
                            pc.DepartmentId = department.DepartmentId;
                            pc.EquipmentId = equipment.EquipmentID;
                            pc.Description = row.GetCell(0).ToString();
                            pc.DescriptionColor = Common.ColorMapping.GetColor(row.GetCell(0).CellStyle.FillForegroundColor);
                            pc.InnerWire =
                                row.GetCell(1) == null ? "" : row.GetCell(1).ToString();
                            pc.TerminalNo = row.GetCell(2).ToString();

                            if (j == 1)
                            {
                                pc.IsTitle = true;
                                generalTerminal = row.GetCell(2).ToString();
                                pc.FullTerminalNo = generalTerminal;
                                pc.FatheTerminalNo = "";
                            }
                            else
                            {
                                pc.FullTerminalNo = generalTerminal + row.GetCell(2).ToString();
                                pc.FatheTerminalNo = generalTerminal;
                            }

                            pc.TerminalNoColor = Common.ColorMapping.GetColor(row.GetCell(2).CellStyle.FillForegroundColor);
                            pc.OuterWire =
                                row.GetCell(3) == null ? "" : row.GetCell(3).ToString();
                            pc.CircuitNo = row.GetCell(4) == null ? string.Empty : row.GetCell(4).ToString();

                            var selectedVoltage = lbVolt.SelectedItems[0] as Voltage;
                            pc.VoltageId = selectedVoltage.VoltageID;

                            var selectedSeperatorType = lbSeperatorType.SelectedItems[0] as SeperatorType;
                            pc.SeperatorTypeId = selectedSeperatorType.SeperatorTypeID;

                            var selectedUnitAndSeperatorName = dataGridView1.SelectedItems;
                            List<Guid> unitId = new List<Guid>();
                            foreach (var item in selectedUnitAndSeperatorName)
                            {
                                Unit unit = item as Unit;
                                unitId.Add(unit.UnitID);
                            }
                            pc.UnitId = string.Join(",", unitId.ToArray());

                            if (PreviousColor == row.GetCell(2).CellStyle.FillForegroundColor)
                            {
                                pc.ShortConnectTo = PreviousGuid;
                                PreviousColor = -1;
                            }
                            else
                            {
                                PreviousGuid = pc.LoopLineId;
                                PreviousColor = row.GetCell(2).CellStyle.FillForegroundColor;
                            }
                            context.LoopLines.Add(pc);
                        }
                    }
                    context.SaveChanges();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private UnitComposite SaveUnitComposite()
        {
            List<Unit> selectedUnit = new List<Unit>();
            List<string> unitAndSeperatorNameList = new List<string>();
            string unitAndSeperatorName = string.Empty;
            foreach (var item in dataGridView1.SelectedItems)
            {
                var unit = item as Unit;
                selectedUnit.Add(unit);
                unitAndSeperatorNameList.Add(unit.UnitName + "," + unit.SepertorName);
            }

            var selectedSeperatorType = lbSeperatorType.SelectedItem as SeperatorType;

            UnitComposite unitComposite = new UnitComposite()
            {
                UnitCompositeId = Guid.NewGuid(),
                UnitIds = string.Join(",", selectedUnit.Select(s => s.UnitID).ToArray()),
                UnitAndSeperatorName = string.Join(";", unitAndSeperatorNameList.ToArray()),
                SeperatorTypeId = selectedSeperatorType.SeperatorTypeID
            };

            context.UnitComposites.Add(unitComposite);
            context.SaveChanges();
            return unitComposite;
        }

        private Equipment SaveSingleEquipment(string filePath, UnitComposite unitComposite)
        {
            string fileName = System.IO.Path.GetFileName(filePath);
            var selectedSeperatorType = lbSeperatorType.SelectedItems[0] as SeperatorType;
            var equipment = new Equipment()
            {
                EquipmentID = Guid.NewGuid(),
                EquipmentName = fileName.Replace(".xls", ""),
                SeperatorTypeId = selectedSeperatorType.SeperatorTypeID,
                UnitCompositeId = unitComposite.UnitCompositeId
            };
            context.Equipments.Add(equipment);
            context.SaveChanges();
            return context.Equipments.Where(s => s.EquipmentID == equipment.EquipmentID).FirstOrDefault();
        }

        public IWorkbook GetWorkBook(string filePath)
        {
            IWorkbook wk = null;
            string extension = System.IO.Path.GetExtension(filePath);
            using (FileStream fs = File.OpenRead(filePath))
            {
                if (extension.Equals(".xls"))
                {
                    wk = new HSSFWorkbook(fs);
                }
                else
                {
                    wk = new XSSFWorkbook(fs);
                }
            }
            return wk;
        }

        private void btnUnitAndSeperatorAdd_Click(object sender, RoutedEventArgs e)
        {
            string unit = txtUnit.Text.Trim();
            string seperatorName = txtSeperatorName.Text.Trim();
            var selectedSeperatorTypeId = (lbSeperatorType.SelectedItems[0] as SeperatorType).SeperatorTypeID;
            if (string.IsNullOrEmpty(unit) || string.IsNullOrEmpty(seperatorName))//判空
            {
                System.Windows.Forms.MessageBox.Show("输入值不能为空,请重新输入！");
                return;
            }

            if (context.Units.Where(u => u.SeperatorTypeID == selectedSeperatorTypeId).Any(u => u.UnitName == unit) || context.Units.Where(u => u.SeperatorTypeID == selectedSeperatorTypeId).Any(u => u.SepertorName == seperatorName)) //是否存在
            {
                System.Windows.Forms.MessageBox.Show("输入值已经存在,请重新输入！");
                txtUnit.Text = string.Empty;
                txtSeperatorName.Text = string.Empty;
                return;
            }

            var selectedSeperatorType = lbSeperatorType.SelectedItems[0] as SeperatorType;
            Unit Unit = new Unit()
            {
                UnitID = Guid.NewGuid(),
                SeperatorTypeID = selectedSeperatorType.SeperatorTypeID,
                SepertorName = seperatorName,
                UnitName = unit
            };

            context.Units.Add(Unit);
            context.SaveChanges();
            txtUnit.Text = string.Empty;
            txtSeperatorName.Text = string.Empty;
            LoadUnitAndSeperatorName();
        }

        private void ClearUnitAndSeperatorName()
        {
            txtSeperatorName.Text = string.Empty;
            txtUnit.Text = string.Empty;
            dataGridView1.ItemsSource = null;
        }

        private void lbSeperatorType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbSeperatorType.SelectedItems.Count > 0)
            {
                this.btnUnitAndSeperatorAdd.IsEnabled = true;
                LoadUnitAndSeperatorName();
            }
            else
            {
                ClearUnitAndSeperatorName();
                this.btnUnitAndSeperatorAdd.IsEnabled = false;
            }
        }

        private void lbVolt_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbVolt.SelectedItems.Count > 0)
            {
                LoadSeperatorType();
            }
        }

        private void btnVoltAdd_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtVolt.Text.Trim()))
            {
                System.Windows.Forms.MessageBox.Show("输入值不能为空,请重新输入！");
                return;
            }
            if (context.Voltages.Where(v => v.ProjectID == project.ProjectID).Any(v => v.VoltageValue == txtVolt.Text.Trim()))
            {
                System.Windows.Forms.MessageBox.Show("输入值已经存在,请重新输入！");
                txtVolt.Text = string.Empty;
                return;
            }

            Voltage voltage = new Voltage()
            {
                ProjectID = this.project.ProjectID,
                VoltageID = Guid.NewGuid(),
                VoltageValue = txtVolt.Text.Trim()
            };

            context.Voltages.Add(voltage);
            context.SaveChanges();
            txtVolt.Text = string.Empty;
            LoadVoltages();
        }

        private void btnSeperatorTypeAdd_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtSeperatorType.Text.Trim()))
            {
                System.Windows.Forms.MessageBox.Show("输入值不能为空,请重新输入！");
                return;
            }

            if (context.SeperatorTypes.Any(s => s.SeperatorValue == txtSeperatorType.Text.Trim()))
            {
                System.Windows.Forms.MessageBox.Show("输入值已经存在,请重新输入！");
                txtSeperatorType.Text = string.Empty;
                return;
            }

            var selectedValtageId = (lbVolt.SelectedItems[0] as Voltage).VoltageID;
            SeperatorType seperatorType = new SeperatorType()
            {
                SeperatorTypeID = Guid.NewGuid(),
                SeperatorValue = txtSeperatorType.Text.Trim(),
                VoltageID = selectedValtageId
            };

            context.SeperatorTypes.Add(seperatorType);
            context.SaveChanges();
            txtSeperatorType.Text = string.Empty;
            LoadSeperatorType();
        }

        private Department SaveDepartment(string sheetName, int sheetIndex, Guid LineProtectBoxId)
        {
            var depart = new Department()
            {
                DepartmentId = Guid.NewGuid(),
                DepartmentName = sheetName,
                EquipmentId = LineProtectBoxId,
                SheetIndex = sheetIndex
            };
            context.Departments.Add(depart);
            context.SaveChanges();
            return context.Departments.Where(s => s.DepartmentId == depart.DepartmentId).FirstOrDefault();
        }

        private void dataGridView1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            if (e.Row.Item != null)
            {
                var selectedUnit = e.Row.Item as Unit;
                if (selectedUnit != null)
                {
                    var dbUnit = context.Units.Where(u => u.UnitID == selectedUnit.UnitID).FirstOrDefault();
                    if (dbUnit != null)
                    {
                        System.Windows.Controls.TextBox t = e.EditingElement as System.Windows.Controls.TextBox;
                        DataGridColumn dgc = e.Column;
                        if (dgc.DisplayIndex == 0)
                        {
                            dbUnit.UnitName = t.Text;
                        }
                        else if (dgc.DisplayIndex == 1)
                        {
                            dbUnit.SepertorName = t.Text;
                        }
                        context.Units.Attach(dbUnit);
                        context.Entry(dbUnit).State = System.Data.Entity.EntityState.Modified;
                        context.SaveChanges();
                    }
                }
            }
        }
    }
}
